package com.bamboo.framework.framework.security.config;


import com.bamboo.framework.framework.security.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SpringSecurityConf extends WebSecurityConfigurerAdapter {
    /**
     * 未登陆时返回
     */
    @Autowired
    AjaxAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 登录成功返回的
     */
    @Autowired
    AjaxAuthenticationSuccessHandler authenticationSuccessHandler;

    /**
     * 登录失败返回的
     */
    @Autowired
    AjaxAuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 注销成功返回的
     */
    @Autowired
    AjaxLogoutSuccessHandler logoutSuccessHandler;

    /**
     * 无权访问返回的
     */
    @Autowired
    AjaxAccessDeniedHandler accessDeniedHandler;

    /**
     * 自定义安全认证
     */
    @Autowired
    UserServiceImpl userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
         .and().authorizeRequests().anyRequest().authenticated()
         // 其他 url 需要身份认证
         .and() .formLogin()
         .loginProcessingUrl("/user/login")
         //开启登录
         .successHandler(authenticationSuccessHandler)
         .failureHandler(authenticationFailureHandler)
         .permitAll() .and() .logout() .logoutSuccessHandler(logoutSuccessHandler) .permitAll();
          //无权访问 JSON 格式的数据
         http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }


}
